package com.prisetree.isv.controller.admin;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.prisetree.isv.common.constant.ConstantsUtil;
import com.prisetree.isv.domain.User;
import com.prisetree.isv.service.IsvUserService;

@Controller
public class SysLoginController {

	@Autowired
	private IsvUserService isvUserService;

	@RequestMapping(value = "/admin", method = RequestMethod.GET)
	public String adminPage() {
		return "login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginPage() {
		return "redirect:/admin";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(User user, Model model, HttpServletRequest request) {
		String errorMsg = null;

		if (user == null || StringUtils.isBlank(user.getMobile())) {// TODO  mobile ? username?
			errorMsg = "请输入用户名";
		}
		if (StringUtils.isBlank(user.getPassword())) {
			errorMsg = "请输入密码";
		}

		User domain = isvUserService.getByMobile(user.getMobile());
		if (domain == null) {
			errorMsg = "用户不存在";
		} else if (!StringUtils.equals(domain.getUserType(), User.USER_TYPE_ADMIN)) {
			errorMsg = "非管理员用户禁止登录";
		} else if (!StringUtils.equals(user.getPassword(), domain.getPassword())) {
			errorMsg = "密码错误";
		}
		if (StringUtils.isNotBlank(errorMsg)) {
			model.addAttribute("errMsg", errorMsg);
			return "login";
		}

		request.getSession().setAttribute(ConstantsUtil.SESSION_CURRENT_USER, domain);
		return "redirect:/index";
	}

	// @RequestMapping(value = "/logout")
	// public String logout(Model model) {
	// request.getSession().removeAttribute(ConstantsUtil.SESSION_CURRENT_USER);
	//
	// return "admin/login";
	// }

	@RequestMapping(value = { "welcome" }, method = RequestMethod.GET)
	public String welcome() {
		return "welcome";
	}

}
